<?php
namespace Home\Controller;

use Think\Controller;

class CustomizedController extends BaseController
{

    /**
     * 获取定制商品列表
     */
    public function getCustomizedList()
    {
        $page = (int)I('p') ? (int)I('p') : 0;
        $list = 10;
        $customList = M("customized")->where(array("isDelete"=>2))->limit($page*$list, $list)->order("id asc")->select();
        $this->ajaxSuccess($customList);
    }

    //获取定制商品详情
    public function getCustomizedDetail(){
        $id = (int)I('get.id');
        if (empty($id)) $this->ajaxError("参数错误：未知的id！");
        $detail = M("customized")
            ->where(array(
                "id"=>$id,
                "isDelete"=>2,
            ))
            ->find();
        if (!$detail) {
            $this->ajaxError("定制产品不存在或已删除！");
        }
        if (!empty($detail['imgs'])) {
            $img_arr = explode(',', $detail['imgs']);
            $detail['img_arr'] = $img_arr;
        } else {
            $detail['img_arr'][0] = $detail['img'];
        }

        return $this->ajaxSuccess(array('detail'=>$detail));
    }

    /**
     * 定制动作
     */
    public function customized()
    {
        parent::loginCheck();

        //身份信息是否完善
        A("member")->satisfyInformation();

        $member = parent::get('account');

        $memberId = $member['id']; //当前用户id
        $id = (int)I('post.id'); //定制产品id

        if (empty($id)) $this->ajaxError("参数错误：未知的定制产品id！");

        $detail = M("customized")
            ->where(array(
                "id"=>$id,
                "isDelete"=>2,
            ))
            ->find();
        if (!$detail) {
            $this->ajaxError("定制产品信息不存在或已删除！");
        }

        $data = array(
            "memberId" => $memberId,
            "customizedId" => $id,
            "createdTime" => now_datetime(),
            "status" => 1, //下单
        );

        $res = M("mycustomized")->add($data);

        //销量+1
        M("customized")->where(array("id"=>$id))->setInc("num", 1);
        if ($res) {
            $this->ajaxSuccess("定制成功！");
        } else {
            $this->ajaxError("操作失败");
        }
    }

    /**
     * 我的定制产品列表
     */
    public function myCustomized()
    {
        parent::loginCheck();

        $page = (int)I('p') ? (int)I('p') : 0;
        $list = 10;

        $memberId = parent::get('account')['id']; //当前用户id
        $myCustomized = M("mycustomized")
            ->alias("m")
            ->field("m.*,c.name,c.img,c.price")
            ->join("left join t_customized c ON m.customizedId=c.id")
            ->where(array("memberId"=>$memberId))
            ->limit($page*$list, $list)->select();

        $this->ajaxSuccess($myCustomized);
    }
}
